var express = require('express');
var router = express.Router();
let db = require('../utils/db');//打开数据库连接\
let connection = db.connection();//打开数据库连接
let appConfig = require('../utils/app-config');//基础配置
let userModel=require("../model/userModel");

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

//获取所有用户
router.get('/getUser', function (req, res, next) {
  connection.query("select * from user", (e, d, f) => {
    if (e) { res.json(appConfig.errorJson(e)); }
    res.json(Object.assign(appConfig.successJson(), { data: d }));
  });
});

//新增用户
router.post('/addUser', function (req, res, next) {
  var body = req.body;
  var sql = `INSERT INTO user (name, sex) VALUES ('${body.name}','${body.sex}')`;
  connection.query(sql, function (e, d, f) {
    if (e) { res.json(appConfig.errorJson(e)); }
    res.json(appConfig.successJson());
  });
});
//修改用户
router.post('/updateUser', function (req, res, next) {
  var body = req.body;
  var user=userModel;
  connection.query("UPDATE user SET name='" + body.name + "', sex='" + body.sex + "' WHERE id='" + body.id + "'", (e, d, f) => {
    if (e) { res.json(appConfig.errorJson(e)); }
    res.json(appConfig.successJson());
  });
});
//删除用户
router.post('/deleteUser', function (req, res, next) {
  var body = req.body;
  if (!body.id) {
    res.json(Object.assign(appConfig.successJson(), { msg: "id是必须的" }));
  }
  connection.query("DELETE from user WHERE id='" + body.id + "'", (e, d, f) => {
    if (e) { res.json(appConfig.errorJson(e)); }
    res.json(appConfig.successJson());
  });
});

module.exports = router;
